<template>
  <app-dialog-form
    :title="`${props.ruleId ? '编辑' : '添加'}商品规格`"
    :confirm="handleSubmit"
    width="800px"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="form"
      :inline="true"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      size="small"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="20">
          <el-form-item
            label="规格模版名称"
            prop="rule_name"
          >
            <el-input
              v-model="formData.rule_name"
              placeholder="请输入规格模版名称"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <app-draggable
          v-model="formData.spec"
          :options="{
            handle: '.el-icon-menu'
          }"
        >
          <el-form-item
            v-for="(item, index) in formData.spec"
            :key="item.value"
            :label="item.value"
          >
            <template #label>
              <i class="el-icon-menu" />
            </template>
            <div>
              <el-tag
                closable
                effect="dark"
                @close="formData.spec.splice(index, 1)"
              >
                {{ item.value }}
              </el-tag>
            </div>
            <div>
              <app-draggable
                style="display: inline-block;"
                v-model="item.detail"
              >
                <el-tag
                  class="detail-item"
                  v-for="(detail, detailIndex) in item.detail"
                  :key="detail"
                  closable
                  effect="plain"
                  @close="item.detail.splice(detailIndex, 1)"
                >
                  {{ detail }}
                </el-tag>
              </app-draggable>
              <el-input
                class="input-new-tag"
                v-model="item.tmpDetail"
                ref="saveTagInput"
                placeholder="请输入属性名称"
                size="mini"
              >
                <template #append>
                  <el-button
                    size="mini"
                    type="primary"
                    @click="confirmTmpDetail(item, index)"
                  >
                    添加
                  </el-button>
                </template>
              </el-input>
            </div>
          </el-form-item>
        </app-draggable>
      </el-row>
      <el-row v-if="isTmpSpecShow">
        <el-form-item
          label="规格名称"
        >
          <el-input
            size="small"
            v-model="tmpSpec.value"
            placeholder="请输入规格名称"
          />
        </el-form-item>
        <el-form-item label="规格值">
          <el-input
            size="small"
            v-model="tmpSpec.detail[0]"
            placeholder="请输入规格值"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            type="primary"
            @click="onSubmitTmpSpec"
          >
            确定
          </el-button>
          <el-button
            size="small"
            @click="resetTmpSpec"
          >
            取消
          </el-button>
        </el-form-item>
      </el-row>

      <el-button
        type="primary"
        icon="el-icon-plus"
        class="add-rule-btn"
        v-if="!isTmpSpecShow"
        @click="isTmpSpecShow = true"
      >
        添加商品规格
      </el-button>
    </el-form>
  </app-dialog-form>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { PropType } from 'vue'
import type { IElForm, IFormRule } from '@/types/element-plus'
import { ElMessage } from 'element-plus'
import type { RuleForm, RuleSpec } from '@/api/types/product'
import { getRuleDetail, saveAttrRule } from '@/api/product'

const props = defineProps({
  ruleId: { // 编辑的商品分类 ID
    type: Number as PropType<number | undefined>,
    default: undefined
  }
})

interface EmitsType {
  (e: 'update:rule-id', value: number | null): void
  (e: 'success'): void
}

const emit = defineEmits<EmitsType>()

const form = ref<IElForm | null>(null)
const formLoading = ref(false)
const formData = ref<RuleForm>({
  id: undefined,
  rule_name: '',
  rule_value: '',
  spec: []
})

const formRules = ref<IFormRule>({
  rule_name: [
    { required: true, message: '请输入规格模版名称', trigger: 'blur' }
  ]
})

formLoading.value = true
const handleDialogOpen = () => {
  formLoading.value = true
  loadRuleDetail().finally(() => {
    formLoading.value = false
  })
}
const defaultTmpSpec = {
  value: '',
  detail: ['']
}
const tmpSpec = ref<RuleSpec>(JSON.parse(JSON.stringify(defaultTmpSpec)))

const isTmpSpecShow = ref(false)

const onSubmitTmpSpec = () => {
  if (tmpSpec.value.detail[0] !== '' && tmpSpec.value.value !== '') {
    if (formData.value.spec.find(item => item.value === tmpSpec.value.value)) {
      ElMessage.warning('已存在同名规格')
    } else {
      formData.value.spec.push(JSON.parse(JSON.stringify(tmpSpec.value)))
      resetTmpSpec()
    }
  } else {
    ElMessage.warning('请输入规格和属性名')
  }
}

const resetTmpSpec = () => {
  isTmpSpecShow.value = false
  tmpSpec.value = JSON.parse(JSON.stringify(defaultTmpSpec))
}

const confirmTmpDetail = (spec: RuleSpec, index: number) => {
  if (spec.tmpDetail && spec.tmpDetail !== '') {
    if (formData.value.spec[index].detail.includes(spec.tmpDetail)) {
      ElMessage.warning('此规格已存在相同属性')
    } else {
      formData.value.spec[index].detail.push(spec.tmpDetail)
      spec.tmpDetail = ''
    }
  } else {
    ElMessage.warning('属性不可为空')
  }
}

const loadRuleDetail = async () => {
  if (!props.ruleId) {
    return
  }
  const { info } = await getRuleDetail(props.ruleId)
  formData.value = info
}

const handleDialogClosed = () => {
  emit('update:rule-id', null)
  form.value?.clearValidate() // 清除验证结果
  form.value?.resetFields() // 清除表单数据
}

const handleSubmit = async () => {
  const valid = await form.value?.validate()
  if (!valid) {
    return
  }
  await saveAttrRule(formData.value, props.ruleId)
  formData.value.spec = []
  resetTmpSpec()
  emit('success')
  ElMessage.success('保存成功')
}

</script>

<style lang="scss" scoped>
.add-rule-btn {
  margin-left: 80px;
}
.input-new-tag {
  width: 150px;
  margin-left: 10px;
  vertical-align: bottom;
  .el-button {
    background-color: #409EFF;
    color: white;
    border: none;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    padding: 0px 10px;
  }
}
</style>
